<template>
    <div class="popularizeEdit">
        <h5>创建活动</h5>
        <div class="essential">
            <div class="essential-l">
                <h3>基本信息</h3>
                <ul>
                    <li>
                        <p>
                            <span>*</span>
                            <span>活动名称</span>
                        </p>
                        <el-input v-model="activityName" maxlength="20" show-word-limit placeholder="如：邀请你一起玩转社区"></el-input>
                    </li>
                </ul>
            </div>
        </div>
        <div class="essential-table">
            <ul>
                <li>
                    <p>
                        <span>*</span>
                        <span>活动奖励</span>
                    </p>
                    <div class="table-one">
                        <div class="table-one-title">
                            <span>一、推广者奖励</span>
                            <span @click="chooseClick(1)">选择</span>
                        </div>
                        <el-table :data="rewardPromoter" style="width:100%">
                            <el-table-column label="类目">
                                <template slot-scope="scope">
                                    <span v-if="scope.row.category==1">优惠券</span>
                                    <span v-if="scope.row.category==2">积分</span>
                                    <span v-if="scope.row.category==3">金币</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="类型">
                                <template slot-scope="scope">
                                    <span v-if="scope.row.faceType==1">现金券</span>
                                    <span v-else-if="scope.row.faceType==2">折扣</span>
                                    <span v-else-if="scope.row.faceType==3">满减券</span>
                                    <span v-else>/</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="rewName" label="名称"></el-table-column>
                            <el-table-column label="适用范围">
                                <template slot-scope="scope">
                                    <span v-if="scope.row.applyLimits==1">商户</span>
                                    <span v-else-if="scope.row.applyLimits==0">全平台</span>
                                    <span v-else-if="scope.row.applyLimits==2">商品</span>
                                    <span v-else>
                                        <span v-if="scope.row.category==2">可提现</span>
                                        <span v-if="scope.row.category==3">直播间可用</span>
                                    </span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="rewNum" label="数量"></el-table-column>
                            <el-table-column label="操作">
                                <template slot-scope="scope">
                                    <el-button @click="handleClick(1,scope.$index,scope.row)" type="text" size="small">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div class="table-one" style="margin-top:20px;">
                        <div class="table-one-title">
                            <span>二、被推广者奖励</span>
                            <span  @click="chooseClick(2)">选择</span>
                        </div>
                        <el-table :data="rewardPromotered" style="width:100%">
                            <el-table-column label="类目">
                                <template slot-scope="scope">
                                    <span v-if="scope.row.category==1">优惠券</span>
                                    <span v-if="scope.row.category==2">积分</span>
                                    <span v-if="scope.row.category==3">金币</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="类型">
                                <template slot-scope="scope">
                                    <span v-if="scope.row.faceType==1">现金券</span>
                                    <span v-else-if="scope.row.faceType==2">折扣</span>
                                    <span v-else-if="scope.row.faceType==3">满减券</span>
                                    <span v-else>/</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="rewName" label="名称"></el-table-column>
                            <el-table-column label="适用范围">
                                <template slot-scope="scope">
                                    <span v-if="scope.row.applyLimits==1">商户</span>
                                    <span v-else-if="scope.row.applyLimits==0">全平台</span>
                                    <span v-else-if="scope.row.applyLimits==2">商品</span>
                                    <span v-else>
                                        <span v-if="scope.row.category==2">可提现</span>
                                        <span v-if="scope.row.category==3">直播间可用</span>
                                    </span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="rewNum" label="数量"></el-table-column>
                            <el-table-column label="操作">
                                <template slot-scope="scope">
                                    <el-button @click="handleClick(2,scope.$index,scope.row)" type="text" size="small">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </li>
                <li>
                    <p>
                        <span>*</span>
                        <span>活动规则</span>
                    </p>
                    <quill-editor 
                        v-model="activityContent" 
                        ref="myQuillEditor" 
                        :options="editorOption" 
                        @blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
                        @change="onEditorChange($event)">
                    </quill-editor>
                </li>
                <li>
                    <p>
                        <span>*</span>
                        <span>活动时间</span>
                    </p>
                    <el-date-picker
                        v-model="activityDate"
                        type="daterange"
                        range-separator="至"
                        value-format="timestamp"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
                    </el-date-picker>
                </li>
                <li>
                    <p>
                        <span>*</span>
                        <span>是否上架</span>
                    </p>
                    <el-radio v-model="activityRadio" label="1">是</el-radio>
                    <el-radio v-model="activityRadio" label="2">否</el-radio>
                </li>
            </ul>
        </div>
        <div class="mask" v-if="masknum2" @click="masknum2=false">
            <div class="code-box" ref="codeBox">
                <div ref="qrcode" class="code-content"></div>
            </div>
        </div>
        <div class="activityButton">
            <span @click="submit">确定</span>
            <span @click="preview" class="preview">扫码预览</span>
            <span @click="activityCancel">取消</span>
        </div>
        <div class="mask" v-if="masknum">
            <div class="content">
                <p class="content-top">
                    <span>添加{{rewardNum==1?'':'被'}}推广者获得的奖励</span>
                    <span @click="cancelClick"><img src="../assets/img/error.png" alt=""></span>
                </p>
                <div class="content-content">
                    <span class="title">类目</span>
                    <el-select v-model="activityItemValue" placeholder="请选择">
                        <el-option  v-for="item in activityItemOptions"  :key="item.value" :label="item.label"  :value="item.value"></el-option>
                    </el-select>
                    <el-select v-if="activityItemValue==1" v-model="faceTypeValue" placeholder="请选择">
                        <el-option  v-for="item in faceTypeOptions"  :key="item.value" :label="item.label"  :value="item.value"></el-option>
                    </el-select>
                </div>
                <div class="table-box">
                    <el-table :data="activityArr" style="width:100%">
                        <el-table-column prop="lm" label="类目"></el-table-column>
                        <el-table-column label="类型">
                            <template slot-scope="scope">
                                <span v-if="scope.row.faceType==1">现金券</span>
                                <span v-else-if="scope.row.faceType==2">折扣券</span>
                                <span v-else-if="scope.row.faceType==3">满减券</span>
                                <span v-else>{{scope.row.faceType}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="couponName" label="名称"></el-table-column>
                        <el-table-column label="适用范围">
                            <template slot-scope="scope">
                                <span v-if="scope.row.applyLimits==0">全平台</span>
                                <span v-else-if="scope.row.applyLimits==1">商户</span>
                                <span v-else-if="scope.row.applyLimits==2">商品</span>
                                <span v-else>{{scope.row.applyLimits}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="数量">
                            <template slot-scope="scope">
                                <el-input-number v-model="scope.row.activitynum" :min="0" :max="scope.row.issueNum" :controls="false" :precision="0"></el-input-number>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button @click="deleteActivityArr(scope.$index,scope.row)" type="text" size="small">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="activityButton maskButton">
                    <span @click="maskSubmit">确定</span>
                    <span @click="cancelClick">取消</span>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import cropImg from "@/components/assembly/cropImg.vue";
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';

import QRCode from 'qrcodejs2'
import html2canvas from 'html2canvas'

export default {
    components: {
        quillEditor,cropImg
    },
    data(){
        return{
            url:'',//转二维码的链接
            baseurl:'',//新人推广
            baseurly:'',//优惠券
            uname:'',//登录名
            type:0,
            editId:'',//编辑数据id
            activityName:'',//活动名称
            activityImg:'',//活动背景图
            rewardNum:1,//打开推广者-1,被推广者-2
            rewardPromoter:[],//推广者奖励数组
            rewardPromotered:[],//被推广者奖励数组
            activityContent:'',//活动规则
            activitycreateTime:'',
            editorOption: {},
            activityDate:'',//活动时间
            activityRadio:'1',//是否上架
            masknum:false,
            masknum2:false,
            activityItemValue:'',//奖励类目
            activityItemOptions:[
                {label:'优惠券',value:'1'},
                {label:'积分',value:'2'},
                {label:'金币',value:'3'},
            ],
            faceTypeValue:'',//面值类型
            faceTypeOptions:[
                {label:'现金券',value:'1'},
                {label:'折扣',value:'2'},
                {label:'满减券',value:'3'},
            ],
            activityArr:[],
            rewardList:[],
            //上传图片
            isLt2M:'',
			fileList:[],
            fileUpUrlList:'',
        }
    },
    mounted(){
        this.baseurl=this.$store.state.baseurl2
        this.baseurly=this.$store.state.baseurl
        this.uname = sessionStorage.getItem('uname')
        this.type=this.$route.query.type
        this.editId=this.$route.query.id
        if(this.type==1){
            this.getDatabyid()
        }
    },
    methods:{
        //预览
        preview(){
            var award=0
            this.rewardPromotered.forEach(e=>{
                if(e.category==1){
                    this.axios({
                        url:this.baseurly+'/coupon/listByIds',
                        method:'post',
                        data:[e.couponId],
                    }).then(rest=>{
                        if(rest.data.data[0].faceType==1){
                            award+=rest.data.data[0].faceValue*0.01
                        }else if(rest.data.data[0].faceType==2){
                            award+=rest.data.data[0].moreFaceValue
                        }else{
                            award+=rest.data.data[0].faceValue.split(":")[1]
                        }
                    })
                }else if(e.category==2){//积分
                    award+=e.rewNum*0.01
                }else{
                    award+=e.rewNum*0.1
                }
            })
            if(this.activityName&&this.activityDate.length==2){
                this.url='https://jbhotel.cklock.cn/sharepreview/#/?extName='+this.activityName+'&startTime='+this.activityDate[0]+'&endTime='+this.activityDate[1]+'&award='+award
                this.initCode()
                this.masknum2=true
            }else{
                this.$message('请填写必填内容')
            }
        },
        initCode() {
            // 使用$nextTick确保数据渲染
            this.$nextTick(() => {
                if (this.url) {
                    this.codeWidth = Number(this.$refs.codeBox.clientHeight)
                    this.codeHeight = Number(this.$refs.codeBox.clientWidth)
                    this.showCode(this.codeWidth, this.codeHeight)
                }
            })
        },
        showCode(width, height) {
            console.log('url',this.url)
            if (this.$refs.qrcode) {
                this.$refs.qrcode.innerHTML = ''
            }
            const qrcode = new QRCode(this.$refs.qrcode, {
                text: this.url, //要跳转的链接
                width: 200,
                height: 200,
                colorDark: '#333333', // 二维码颜色
                colorLight: '#ffffff', // 二维码背景色
                correctLevel: QRCode.CorrectLevel.L// 容错率，L/M/H
            })
            this.createPicture()
        },
        createPicture() {
            html2canvas(this.$refs.qrcode, {
                backgroundColor: null,
                width: 200,
                height: 200
            }).then(canvas => {
                const imgData = canvas.toDataURL('image/jpeg')
                this.imgData = imgData
            })
        },
        shopLogoChild(res) {
            // this.fileUpUrlList = res
        },
        //editId获取编辑内容
        getDatabyid(){
            var extensionEntity={
                id: this.editId,
            }
            this.axios({
                url:this.baseurl+'/public/extension/extension/getlist',
                method:'post',
                data:extensionEntity,
            }).then(res=>{
                if(res.data.code==0){
                    var aaa=res.data.data[0]
                    this.activityName=aaa.extName
                    this.fileList= [{name: '背景图', url: aaa.backPhoto}]
                    // this.fileUpUrlList=aaa.backPhoto
                    this.activityContent=aaa.remarks
                    this.activityRadio=aaa.state
                    this.activitycreateTime=aaa.createTime
                    this.activityDate=[aaa.startTime*1000,aaa.endTime*1000]
                    aaa.rewardList.forEach(e => {
                        if(e.couponId){
                            this.axios({
                                url:this.baseurly+'/coupon/listByIds',
                                method:'post',
                                data:[e.couponId],
                            }).then(rest=>{
                                e.faceType=rest.data.data[0].faceType
                                e.applyLimits=rest.data.data[0].applyLimits
                                if(e.rewardPersion==1){
                                    this.rewardPromoter.push(e)
                                }else{
                                    this.rewardPromotered.push(e)
                                }
                            })
                        }else{
                            if(e.rewardPersion==1){
                                this.rewardPromoter.push(e)
                            }else{
                                this.rewardPromotered.push(e)
                            }
                        }
                    });
                    console.log(this.rewardPromoter)
                    console.log('rewardPromotered',this.rewardPromotered)
                }
            })
        },
        //提交
        submit(){
            this.rewardList=this.rewardPromoter.concat(this.rewardPromotered)
            if(!this.activityName||this.rewardList.length==0||!this.activityContent||this.activityDate.length==0){
                this.$message('请填写必填内容')
                return
            }
            var extensionEntity={
                "backPhoto": '',
                "createTime":Date.parse( new Date())/1000,
                "endTime": this.activityDate[1]/1000,
                "extName": this.activityName,
                "id": 0,
                "remarks": this.activityContent,
                "rewardList": this.rewardList,
                "startTime": this.activityDate[0]/1000,
                "state": this.activityRadio,
            }
            var url='/public/extension/create'
            var msg='保存'
            if(this.type==1){
                url='/public/extension/update/extension'
                extensionEntity.id=this.editId
                extensionEntity.createTime=this.activitycreateTime
                extensionEntity.updateTime=Date.parse( new Date())/1000
                msg='修改'
            }
            this.axios({
                url:this.baseurl+url,
                method:'post',
                data:extensionEntity,
            }).then(res=>{
                if(res.data.code==0){
                    this.$message(msg+'成功')
                    this.$router.push('/index/marketingPopularize')
                }else{
                    alert(res.data.errmsg)
                }
            })
        },
        //取消
        activityCancel(){
            this.activityName=''
            this.rewardPromoter=[]
            this.rewardPromotered=[]
            this.activityContent=''
            this.activityDate=''
            this.$router.push('/index/marketingPopularize')
        },
        //删除推广者、被推广者奖励
        handleClick(n,index,row){
            if(n==1){
                this.rewardPromoter.splice(index,1)
            }else{
                this.rewardPromotered.splice(index,1)
            }
        },
        //获取优惠券列表
        getCoupon(){
            var agreementEntity={
                "busKey":6,
                "faceType":this.faceTypeValue,
                "limit":100,
                "page":1
            }
            this.axios({
                url:this.baseurly+'/coupon/list',
                method:'post',
                data:agreementEntity,
            }).then(res=>{
                if(res.data.code==200){
                    this.activityArr=res.data.data.list
                    this.activityArr.forEach(e=>{
                        e.lm="优惠券"
                        e.activitynum=0
                    })
                }else{
                    alert(res.data.errmsg)
                }
            })
        },
        //弹窗提交
        maskSubmit(){
            if(this.activityItemValue==1){
                var obj={}
                this.activityArr.forEach(e=>{
                    obj={
                        "faceType":e.faceType,
                        "applyLimits":e.applyLimits,
                        "category": this.activityItemValue,
                        "couponId": e.id,
                        "extId": 0,
                        "id": 0,
                        "rewName": e.couponName,
                        "rewNum": e.activitynum,
                        "rewardPersion": this.rewardNum,
                        "typeName": ""
                    }
                    if(this.rewardNum==1&&obj.rewNum!=0){this.rewardPromoter.push(obj)}
                    else if(this.rewardNum==2&&obj.rewNum!=0){this.rewardPromotered.push(obj)}
                })
            }else{
                var obj={
                    "applyLimits":this.activityArr[0].applyLimits,
                    "faceType":'/',
                    "category": this.activityItemValue,
                    "couponId": 0,
                    "extId": 0,
                    "id": 0,
                    "rewName": this.activityArr[0].couponName,
                    "rewNum": this.activityArr[0].activitynum,
                    "rewardPersion": this.rewardNum,
                    "typeName": ""
                }
                if(this.rewardNum==1&&obj.rewNum!=0){this.rewardPromoter.push(obj)}
                else if(this.rewardNum==2&&obj.rewNum!=0){this.rewardPromotered.push(obj)}
            }
            this.activityItemValue=''
            this.faceTypeValue=''
            this.activityArr=[]
            this.masknum=false
            console.log('rewardPromotered',this.rewardPromotered)
        },
        //删除优惠券
        deleteActivityArr(index,row){
            this.activityArr.splice(index,1)
        },
        //点击打开选择按钮
        chooseClick(n){
            this.rewardNum=n
            this.masknum=true
        },
        //关闭弹窗
        cancelClick(){
            this.activityItemValue=''
            this.faceTypeValue=''
            this.activityArr=[]
            this.masknum=false
        },
        //失去焦点事件
        onEditorBlur(quill) {
            console.log('editor blur!', quill)
        },
        //获得焦点事件
        onEditorFocus(quill) {
            console.log('editor focus!', quill)
        },
        //内容改变事件
        onEditorChange({ quill, html, text }) {
            console.log('editor change!', quill, html, text)
            this.activityContent = html
        },
        imgeditClick(){

        },
        handlePreview(file) {
            console.log(file);
        },
        //删除图片
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        //删除提示
        beforeRemove(file, fileList) {
            if(!this.isLt2M){
                return this.$alert('只能上传jpg/png文件，且不超过5MB', '图片上传限制', {confirmButtonText: '确定',});
            }
            return this.$confirm(`确定移除 ${ file.name }？`);
        },
        //提示上传文件个数
        handleExceed(files, fileList) {
            this.$message.warning("只能上传一个文件，请先删除，再上传新文件！");
        },
        //提示上传文件大小
        beforeUpload(file){
            const isLt2M = file.size / 1024 / 1024 < 5;
            this.isLt2M=isLt2M
            console.log(file.size,isLt2M)
            if (!isLt2M) {
                // this.common.errorTip('上传文件大小不能超过 2MB!');
                // this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isLt2M;
        },
        uploadHttp(params){
            var  formData = new FormData();
            formData.append('file', params.file);
            this.axios.post('https://jbhotel.cklock.cn/api/File/uplode', formData, { headers: { 'content-Type': 'multipart/form-data'} }).then(res=> {
                // this.fileUpUrlList=res.data.data
            })
        },
    },
    watch:{
        url(val) {
            console.log("val", val)
            this.initCode()
        },
        activityItemValue(){
            this.faceTypeValue=''
            if(this.activityItemValue==2){
                this.activityArr=[{
                    lm:'积分',
                    faceType:'/',
                    couponName:'新用户注册',
                    applyLimits:'可提现',
                    activitynum:0
                }]
            }else if(this.activityItemValue==3){
                this.activityArr=[{
                    lm:'金币',
                    faceType:'/',
                    couponName:'新用户注册',
                    applyLimits:'直播间可用',
                    activitynum:0
                }]
            }else{
                this.getCoupon()
            }
        },
        faceTypeValue(){
            this.getCoupon()
        }
    }
}
</script>

<style scoped>
.preview{
    cursor: pointer
}
.essential{
    padding: 20px 10px;
    display: flex;
}
.essential-l{
    width: 60%;
}
.essential-l h3{
    font-size: 18px;
    margin: 20px 0;
}
ul li p{
    margin: 20px 0;
}
ul li p span:first-child{
    color: red;
    display: inline-block;
    padding-right: 6px;
}
.essential-r{
    position: relative;
    color: #fff;
}
.essential-r .backg-img{
    width: 230px;
    height: 330px;
    overflow: hidden;
    border: 1px solid #333;
}
.essential-r .backg-img img{
    width: 100%;
}
.essential-r .uname,.essential-r .title{
    width: 230px;
    font-size: 14px;
    text-align: center;
    position: absolute;
    z-index: 99;
    top: 10px;
}
.essential-r .title{
    top: 30px;
}
.table-one .table-one-title{
    margin-bottom: 15px;
}
.table-one .table-one-title span:last-child{
    color: rgb(0, 102, 255);
    padding-left: 30px;
}
.activityButton{
    margin-top: 80px;
    text-align: center;
}
.activityButton span{
    display: inline-block;
    padding: 4px 20px;
    border-radius: 3px;
    font-size: 15px;
    margin-right: 15px;
}
.activityButton span:first-child{
    background: #FDD94C;
    border: 1px solid #FDD94C;
}
.activityButton span:nth-child(2){
    border: 1px solid #FDD94C;
    color: #FDD94C;
}
.activityButton span:nth-child(3){
    border: 1px solid #aaa;
    color: #aaa;
}

/* 遮罩层 */
.mask{
    width: 100vw;
    height: 100vh;
    /* color: #555; */
    background: rgba(51, 51, 51, 0.692);
    position: fixed;
    z-index: 99;
    top: 0;
    left: 0;
}
.mask .content{
    width: 750px;
    height: 600px;
    background: #fff;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    padding: 30px;
    padding-bottom: 60px;
    overflow: auto;
}
.mask .content-top{
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #ddd;
    padding-bottom: 10px;
}
.mask .content-top img{
    width: 25px;
}
.mask .content-content{
    margin-top: 30px;
}
.mask .content-content .title{
    padding-right: 20px;
}
.mask .content-content .button{
    border: 1px solid #FDD94C;
    padding: 7px 10px;
    border-radius: 3px;
    margin-left: 10px;
}
.mask .maskButton {
    width: calc(100% - 60px);
    position: absolute;
    bottom: 20px;
}
.mask .table-box{
    height: 365px;
    overflow: auto;
}
.code-box{
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    width: 200px;
    height: 200px;
}
</style>
<style>
.essential-l ul .el-input{
    width: 45%;
}
.table-box .el-input-number {
    width: 70px;
}
</style>